'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  const { action, data } = event;
  
  if (action === 'addWallpapers') {
    const transaction = await db.startTransaction();
    try {
      const results = [];
      const { baseData, picUrls } = data;
      
      for (const [index, picurl] of picUrls.entries()) {
        const insertData = {
          ...baseData,
          picurl: picurl.trim(),
          sortOrder: picUrls.length > 1 ? index : 0
        };
        
        const result = await transaction.collection('iss-wallpaper-image').add(insertData);
        results.push(result);
      }
      
      await transaction.commit();
      return {
        success: true,
        ids: results.map(item => item.id),
        count: results.length
      };
    } catch (e) {
      await transaction.rollback();
      return {
        success: false,
        error: e.message
      };
    }
  }
  
  return { success: false, error: 'Invalid action' };
};